const $ = layui.$;
let form = layui.form;
let table = layui.table;

export default class UpdateFilm {
  constructor(data) {
    this.render();
    this.handel(data);
  }
  render(index) {
    let template = ` 
        <form class="layui-form" action="" lay-filter="updateForm">
            <div class="layui-form-item">
            <label class="layui-form-label">电影名</label>
            <div class="layui-input-block">
            <input type="text" name="name" required lay-verify="required" placeholder="请输入电影名"
              autocomplete="off" class="layui-input">
            </div>
            </div>
            
            <div class="layui-form-item">
              <label class="layui-form-label">电影英文名</label>
              <div class="layui-input-block">
                <input type="text" name="ename" required lay-verify="required" placeholder="请输入电影英文名" autocomplete="off"
                  class="layui-input">
              </div>           
            </div>

            <div class="layui-form-item">
            <label class="layui-form-label">电影类型</label>
            <div class="layui-input-block">
              <input type="text" name="type" required lay-verify="required" placeholder="请输入电影类型" autocomplete="off"
                class="layui-input">
            </div>           
          </div>

            <div class="layui-form-item">
            <label class="layui-form-label">电影状态</label>
            <div class="layui-input-block">
              <select name='status'>
              <option value="0">暂无</option>
              <option value="1">热映</option>
              <option value="2">热播</option>
              <option value="3">待映</option>
              </select>                    
            </div>
            </div> 
            
            <div class="layui-form-item">
              <label class="layui-form-label">上映地区</label>
              <div class="layui-input-block">
                <input type="text" name="area" required lay-verify="required" placeholder="请输入电影上映地区" autocomplete="off"
                  class="layui-input">
              </div>           
            </div>

            <div class="layui-form-item">
              <label class="layui-form-label">电影时长</label>
              <div class="layui-input-block">
                <input type="text" name="time" required lay-verify="required" placeholder="请输入电影时长" autocomplete="off"
                  class="layui-input">
              </div>           
            </div>

            <div class="layui-form-item">
              <label class="layui-form-label">上映日期</label>
              <div class="layui-input-block">
                <input type="text" name="upDate" required lay-verify="required" placeholder="请输入上映时间" autocomplete="off"
                  class="layui-input">
              </div>           
            </div>

            <div class="layui-form-item">
            <label class="layui-form-label">选择年代</label>
            <div class="layui-input-block">
              <select name='year'>
              <option value="2021">2021</option>
              <option value="2020">2020</option>
              <option value="2019">2019</option>
              <option value="2018">2018</option>
              <option value="2017">2017</option>
              <option value="2016">2016</option>
              <option value="2015">2015</option>
              <option value="2014">2014</option>
              <option value="2013">2013</option>
              <option value="2012">2012</option>
              <option value="2011">2011</option>
              <option value="2000-2010">2000-2010</option>
              <option value="90年代">90年代</option>
              <option value="80年代">80年代</option>
              <option value="70年代">70年代</option>
              <option value="更早">更早</option>
              </select>                    
            </div>
            </div> 

            <div class="layui-form-item">
            <label class="layui-form-label">评分</label>
            <div class="layui-input-block">
              <input type="text" name="score" required lay-verify="required" placeholder="请输入电影评分" autocomplete="off"
                class="layui-input">
            </div>           
          </div>
          <div class="layui-form-item">
          <label class="layui-form-label">票房</label>
          <div class="layui-input-block">
            <input type="text" name="count" required lay-verify="required"  autocomplete="off"
              class="layui-input">
          </div>           
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label">想看人数</label>
          <div class="layui-input-block">
            <input type="text" name="want" required lay-verify="required"  autocomplete="off"
              class="layui-input">
          </div>           
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label">剧情简介</label>
          <div class="layui-input-block">
            <input type="textarea" name="intro" required lay-verify="required"  autocomplete="off"
              class="layui-input">
          </div>           
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">电影海报</label>
            <div class="layui-input-block">
            <div class="layui-upload">
              <button type="button" class="layui-btn layui-btn-normal" id="poster">上传图片</button>
              <div class="layui-upload-list">
                <img class="layui-upload-img" id="posterTip" style="width:100px">
                <p id="posterText"></p>
              </div>
            </div>  
            <input type="hidden" id="posterImg" name='poster'>
            </div>
            </div>


            <div class="layui-form-item">
            <label class="layui-form-label">导演</label>
            <div >
            <button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id='addDirector'>点击修改</button>
            </div>
            </div>

            <div id='oldDirectorForm'></div>
            <div id='addDirectorForm'></div>

            <div class="layui-form-item">
            <label class="layui-form-label">演员</label>
            <div >
            <button type="button" class="layui-btn layui-btn-radius" id='addActor'>点击修改</button>
            </div>
            </div>

            <div id='oldActorForm'></div>
            <div id='addActorForm'></div>

            <div class="layui-form-item">
            <label class="layui-form-label">电影图集</label>
            <div class="layui-input-block">
            <div class="layui-upload">
            <button type="button" class="layui-btn" id="images">多图片上传</button> 
             <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
             预览图：
             <div class="layui-upload-list" id="imagesTip"></div>
             </blockquote>
             </div> 
             </div>
             <input type="hidden" id="imagesID" name='images'>
             </div>   

            <input type="hidden" id="updateFilm" name='_id'>
              

            </form>
            `;

    $("#updateFilmTemplate").html(template);
  }
  handel(data) {
    var upload = layui.upload;
    let directorObj = {},//每次新增导演对象
      director = [];//导演数组
    let actorObj = {},//每次新增演员对象
      actor = [];//演员数组
    let a = 0, i = 0;
    layer.open({
      type: 1
      , title: '修改电影'
      , area: ['800px', '500px']
      , shade: 0.5
      , id: 'LAY_layuipro' //设定一个id，防止重复弹出
      , btn: ['确认', '取消']
      , btnAlign: 'c'
      , moveType: 1 //拖拽模式，0或者1
      , content: $('#updateFilmTemplate').html()
      , yes(index) {
        //遍历取到新增的动态表单的值
        //导演
        for (let b = 0; b < a; b++) {
          if ($("#addDirectorForm" + b).length > 0) {
            directorObj = {
              name: $('#director' + b).val(),
              image: $('#imgId' + b).val()
            }
            director.push(directorObj)
          }
        }
        //演员
        for (let b = 0; b < i; b++) {
          if ($('#addActorForm' + b).length > 0) {
            actorObj = {
              name: $('#actor' + b).val(),
              image: $('#imgId-actor' + b).val()
            }
            actor.push(actorObj)
          }
        }
        $.ajax({
          type: 'put',
          url: '/api/films/' + $('#updateFilm').val(),
          data: { ...form.val('updateForm'), director: JSON.stringify(director), actor: JSON.stringify(actor) },
          success(res) {
            table.reload('filmsTable')
          }
        })
        layer.close(index);
        layer.msg('修改电影成功');
      },
      success: function (layero) {
        form.render();
        //获取选中行的电影数据渲染给弹出的表单
        $.ajax({
          type: 'get',
          url: '/api/films/' + data._id,
          success(res) {
            form.val('updateForm', res);
            form.render()
          }
        })
        form.render();
        //新增导演
        $('#addDirector').click(function () {
          layer.msg('请务必先完成当前新增内容后，再进行下一次新增');
          $('#addDirector').prop('disabled',true)
          let template = `
                    <div style=' border: 1px dashed ;margin:20px' id='addDirectorForm${a}'>
                    <div class="layui-form-item" style="margin-top:20px">
                    <label class="layui-form-label">导演</label>
                    <div class="layui-input-block">
                    <input type="text" required lay-verify="required"  autocomplete="off"
                     class="layui-input" id='director${a}'>
                    </div>           
                    </div>

                    <div class="layui-form-item">
            <label class="layui-form-label">导演照片</label>
            <div class="layui-input-block">
            <div class="layui-upload">
              <button type="button" class="layui-btn layui-btn-normal" id='directorImg${a}'>上传图片</button>
              <div class="layui-upload-list">
                <img class="layui-upload-img" id="directorTip${a}" style="width:100px">
                <p id="directorText${a}"></p>
              </div>
            </div>  
            <input type="hidden" id="imgId${a}">
            </div>
            <button type="button" class="layui-btn  layui-btn-radius layui-btn-warm del-director${a}" style="margin-left:100px" data-index=${a}>删除</button>
            <button type="button" class="layui-btn  layui-btn-radius layui-btn-danger con-director${a}"data-index=${a}>确认</button>
            </div>
            </div>
                   `
          $('#addDirectorForm').append(template);
          // console.log(a,'danyan');
          //导演图片上传-------
          var uploadInst = upload.render({
            elem: '#directorImg' + a
            , url: '/upload' //改成您自己的上传接口
            , auto: true
            , before: function (obj) {
              //预读本地文件示例，不支持ie8
              obj.preview(function (index, file, result) {
                $('#directorTip' + a).attr('src', result); //图片链接（base64）
              });
            }
            , done: function (res) {
              //如果上传失败
              if (res.code > 0) {
                return layer.msg('上传失败');
              }
              //上传成功
              layer.msg('上传成功')
              $('#imgId' + a).val(res.filename)
              $('#addDirector').prop('disabled',false)
              a++;
            }
            , error: function () {
              //演示失败状态，并实现重传
              var demoText = $('#directorText' + a);
              demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
              demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
              });
            }
          });
  
          //点击删除移除增加的form
          $('#addDirectorForm').on('click', '.del-director' + a, function () {
            let a = $(this).attr('data-index');
            $('#addDirectorForm' + a).remove();

          })


        })


        //新增演员
        $('#addActor').click(function () {
          layer.msg('请务必先完成当前新增内容后，再进行下一次新增');
          $('#addActor').prop('disabled',true)
          let template = `
         <div style=' border: 1px dashed ;margin:20px' id='addActorForm${i}'>
                    <div class="layui-form-item" style="margin-top:20px">
                    <label class="layui-form-label">演员</label>
                    <div class="layui-input-block">
                    <input type="text" required lay-verify="required"  autocomplete="off"
                     class="layui-input" id='actor${i}'>
                    </div>           
                    </div>

          <div class="layui-form-item">
            <label class="layui-form-label">演员照片</label>
            <div class="layui-input-block">
              <div class="layui-upload">
                <button type="button" class="layui-btn layui-btn-normal" id='actorImg${i}'>上传图片</button>
                  <div class="layui-upload-list">
                   <img class="layui-upload-img" id="actorTip${i}" style="width:100px">
                   <p id="actorText"></p>
                  </div>
              </div>  
             <input type="hidden" id="imgId-actor${i}">
            </div>
            <button type="button" class="layui-btn  layui-btn-radius layui-btn-warm del-actor" style="margin-left:100px" data-index=${i}>删除</button>
            <button type="button" class="layui-btn  layui-btn-radius layui-btn-danger con-actor"data-index=${i}>确认</button>   
           </div>

            </div>
                   `

          $('#addActorForm').append(template);

          //演员图片上传
          var uploadInst = upload.render({
            elem: '#actorImg' + i
            , url: '/upload' //改成您自己的上传接口
            , auto: true
            , before: function (obj) {
              //预读本地文件示例，不支持ie8
              obj.preview(function (index, file, result) {
                $('#actorTip' + i).attr('src', result); //图片链接（base64）
              });
            }
            , done: function (res) {
              //如果上传失败
              if (res.code > 0) {
                return layer.msg('上传失败');
              }
              //上传成功
              layer.msg('上传成功')
              $('#imgId-actor' + i).val(res.filename);
              $('#addActor').prop('disabled',false)
              i++;
            }
            , error: function () {
              //演示失败状态，并实现重传
              var demoText = $('#actorText' + i);
              demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
              demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
              });
            }
          });

          //点击一次i增加一次，更新下一次的ID

          $("#addActorForm").on("click", ".con-actor", function () {
            let i = $(this).attr("data-index");

          });
          $('#addActorForm').on('click', '.del-actor', function () {
            let i = $(this).attr('data-index');
            $('#addActorForm' + i).remove();

          })

        })



        //海报上传
        var uploadInst = upload.render({
          elem: '#poster'
          , url: '/upload' //改成您自己的上传接口
          , auto: true
          , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
              $('#posterTip').attr('src', result); //图片链接（base64）
            });
          }
          , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
              return layer.msg('上传失败');
            }
            //上传成功
            layer.msg('上传成功')
            $('#posterImg').val(res.filename)
          }
          , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#posterText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
              uploadInst.upload();
            });
          }
        });


        //多图片上传-----图集
        upload.render({
          elem: '#images'
          , url: '/upload' //改成您自己的上传接口
          , multiple: true
          , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
              $('#imagesTip').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img" style="height:100px">')
            });
          }
          , done: function (res) {
            if (res.code > 0) {
              return layer.msg('上传失败');
            }
            //上传完毕
            layer.msg('上传成功')
            let content = $('#imagesID').val();//取出表单中原有的值,第一下项值为空
            // console.log(content);
            let imgID = res.filename;//新的图片地址
            let imgArr = []
            imgArr = [content, imgID]//组装成对象
            //  console.log(imgArr);
            $('#imagesID').val(imgArr)//赋值给input框
            // console.log($('#imagesID').val());
          }
        });





      }


    });


  }
}